import contextMenuVue from './ContextMenu.vue'
import { isClient } from '/@/utils/is'
import { CreateContextOptions, ContextMenuProps } from './typing'
import { createVNode, render } from 'vue'

const menuManager: {
  domList: Element[]
  resolve: Fn
} = {
  domList: [],
  resolve: () => {},
}

export function createElement(vnode) {
  // 虚拟dom组成的三要素
  let tag = vnode.tag // 目标元素 ul
  let attrs = vnode.attrs || {} // 属性
  let children = vnode.children || [] // 子节点

  if (!tag) {
    return null
  }
  // 1.创建对应的dom
  let elem = document.createElement(tag)
  let attrName
  // 2.给dom添加属性
  for (attrName in attrs) {
    if (attrName.hasOwnProperty(attrName)) {
      elem.setAttribute(attrName, attrs[attrName])
    }
  }

  // 3。将子元素添加到目标之上
  children.forEach(function (childVnode) {
    elem.appendChild(createElement(childVnode))
  })
  return elem
}
export const createContextMenu = function (options: CreateContextOptions) {
  const { event } = options || {}

  event && event?.preventDefault()

  if (!isClient) {
    return
  }
  return new Promise((resolve) => {
    const body = document.body

    const container = document.createElement('div')
    const propsData: Partial<ContextMenuProps> = {}
    if (options.styles) {
      propsData.styles = options.styles
    }

    if (options.items) {
      propsData.items = options.items
    }

    if (options.event) {
      propsData.customEvent = event
      propsData.axis = { x: event.clientX, y: event.clientY }
    }

    // const vm = createVNode(contextMenuVue, propsData)
    // const vm: any = createElementVNode(contextMenuVue, propsData as any)
    // const vm = createElementVNode('div', {}, 545)
    // console.log(vm)
    // const dom = createElement()
    // container.appendChild(dom)
    // // render(vm, container)
    // document.body.appendChild(container)

    const handleClick = function () {
      menuManager.resolve('')
    }

    menuManager.domList.push(container)

    const remove = function () {
      menuManager.domList.forEach((dom: Element) => {
        try {
          dom && body.removeChild(dom)
        } catch (error) {}
      })
      body.removeEventListener('click', handleClick)
      body.removeEventListener('scroll', handleClick)
    }

    menuManager.resolve = function (arg) {
      remove()
      resolve(arg)
    }
    remove()
    body.appendChild(container)
    body.addEventListener('click', handleClick)
    body.addEventListener('scroll', handleClick)
  })
}

export const destroyContextMenu = function () {
  if (menuManager) {
    menuManager.resolve('')
    menuManager.domList = []
  }
}
